﻿using RightControl.Common;
using RightControl.IService;
using RightControl.Model;
using RightControl.Repository;
using System;
using System.Collections.Generic;
using System.Text;

namespace RightControl.Service {
    public class DhGateService : BaseService<DhGateMeta>, IDhGateService {
        public IDhGateRepository repository { get; set; }
        public static IExportFieldsService exportFieldsService { get; set; }
        public static IBaseCategoryService baseCategoryService { get; set; }

        public dynamic GetListByFilter(DhGateMeta filter, PageInfo pageInfo) {
            string _where = " where 1=1";
            if (!string.IsNullOrEmpty(filter.CategoryCode)) {
                _where += string.Format(" and CategoryCode = '{0}'", filter.CategoryCode);
            }
            _where += string.Format(" and CreateBy = {0}", filter.CreateBy);

            return GetListByFilter(filter, pageInfo, _where);
        }

        public int AddDhGateMeta(ProductDetail productDetail, int userId) {
            if (productDetail != null) {
                var gradeFields = exportFieldsService.GetGradeFields(productDetail.CategoryCode);
                string categoryName = baseCategoryService.GetCategoryName(productDetail.CategoryCode);
                Dictionary<String, String> attrDic = SerializerHelper.JsonDeserialized<Dictionary<string, string>>(productDetail.KeyAttributes);

                DhGateMeta metaData = new DhGateMeta();
                metaData.ProductId = productDetail.Id;
                metaData.CategoryCode = productDetail.CategoryCode;
                metaData.ProductSku = string.Format("{0}{1}", productDetail.SkuId, RightControl.Common.Common.RandomChar());
                metaData.ImageUrl = productDetail.ImageUrl;

                metaData.Title = GetProdTitle(categoryName, attrDic, gradeFields);

                StringBuilder sbDesc = new StringBuilder();
                Dictionary<String, String> keyAttr = SerializerHelper.JsonDeserialized<Dictionary<String, String>>(productDetail.KeyAttributes);
                foreach (KeyValuePair<String, String> item in keyAttr) {
                    if (!string.IsNullOrEmpty(item.Value)) {
                        sbDesc.AppendFormat("<p>{0}: {1}</p>", item.Key.Replace("_", " "), item.Value);
                    }
                }
                metaData.Description = sbDesc.ToString();

                string gFeature = gradeFields.ContainsKey("G") ? gradeFields["G"] : gradeFields["H"];
                if (productDetail.CategoryCode == "CSH") { //鞋类
                    metaData.ShortDesc = "Please check the size chart (*Last Image*) before purchasing | Please Note: Color may vary slightly from image; "
                  + GetAttrValByGrade(attrDic, gradeFields, "I") 
                  + GetAttrValByGrade(attrDic, gradeFields, "G") 
                  + string.Format("This {0} is perfect for vacation, outdoor, wedding, cocktail, party, work or casual occation.", categoryName)
                  + string.Format("Washing introduction: hand wash and hang to dry.");
                } if (productDetail.CategoryCode == "YGF") { //瑜伽服
                    metaData.ShortDesc = "Please check the size chart (*Last Image*) before purchasing | Please Note: Color may vary slightly from image;"
                  + GetAttrValByGrade(attrDic, gradeFields, "I")
                  + string.Format("Feature:{0},{1},{2}", GetAttrValByGrade(attrDic, gradeFields, "E"), GetAttrValByGrade(attrDic, gradeFields, "F"), GetAttrValByGrade(attrDic, gradeFields, "G"))
                  + string.Format("Super soft, lightweight, stretchy and smooth, comfortable and cool, wonderful for workout sports out;")
                  + string.Format("Washing introduction: hand wash, or low temperature for machine washing, and hang to dry.");
                }
                else {
                    //服装类
                    metaData.ShortDesc = "Please check the size chart (*Last Image*) before purchasing | Please Note: Color may vary slightly from image; "
                  + GetAttrValByGrade(attrDic, gradeFields, "H") 
                  + string.Format("Feature:{0},{1},{2}", GetAttrValByGrade(attrDic, gradeFields, "E"), GetAttrValByGrade(attrDic, gradeFields, "F"), GetAttrValByGrade(attrDic, gradeFields, "G"))
                  + string.Format("This {0} is perfect for vacation, outdoor, wedding, cocktail, party, work or casual occation.", categoryName)
                  + string.Format("Washing introduction: hand wash, or low temperature for machine washing, and hang to dry.");
                }              
            
                metaData.KeyWord1 = string.Format("{0} {1}", categoryName, attrDic[gradeFields["B"]]);
                metaData.KeyWord2 = string.Format("{0} {1}", categoryName, attrDic[gradeFields["C"]]);
                metaData.KeyWord3 = categoryName;
                metaData.CreateOn = DateTime.Now;
                metaData.CreateBy = userId;
                return this.InsertModel(metaData);
            }
            else {
                return -1;
            }
        }


        private string GetAttrValByGrade(Dictionary<string, string> attrDic, Dictionary<string, string> gradeFields, string grade) {
            if (gradeFields.ContainsKey(grade)) {
                if (attrDic.ContainsKey(gradeFields[grade])) {
                    return attrDic[gradeFields[grade]];
                }
            }
            return "";
        }


        private String GetProdTitle(string categoryName, Dictionary<String, String> attriDic, Dictionary<string, string> gradeFields) {
            //List<string> keyList5 = new List<string>() { "Gender", "Fabric_Material", "Dresses_Shape", "Pattern_Type", "Sleeves_Length", 
            //                                            "Dresses_Length", "Sleeves_Type", "Collar_Type","Season","Waistline" };
            //A	B+C+D+E	F+G+H+I+J+K+L+M+N+O+P
            List<string> keyList1 = new List<string>() { "B", "C", "D", "E" };
            List<string> keyList2 = new List<string>() { "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R"};
            keyList1 = HtmlUtils.RandomSortList(keyList1);
            keyList2 = HtmlUtils.RandomSortList(keyList2);
            keyList1.AddRange(keyList2);

            string title = "";
            StringBuilder sbTitle = new StringBuilder(categoryName + " ");
            foreach (var item in keyList1) {
                if (gradeFields.ContainsKey(item)) {
                    if (attriDic.ContainsKey(gradeFields[item])) {
                        title = sbTitle.ToString() + attriDic[gradeFields[item]];
                        if (title.Length > 130) break;
                        sbTitle.Append(attriDic[gradeFields[item]] + " ");
                    }
                }
            }

            return sbTitle.ToString().TrimEnd(' ');
        }


    }
}